package com.jincheng.framework.web.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jincheng.common.constant.CacheConstants;
import com.jincheng.common.constant.Constants;
import com.jincheng.common.constant.UserConstants;
import com.jincheng.common.core.domain.entity.SysUser;
import com.jincheng.common.core.domain.model.LoginBody;
import com.jincheng.common.core.domain.model.LoginUser;
import com.jincheng.common.core.domain.model.WxLoginBody;
import com.jincheng.common.core.redis.RedisCache;
import com.jincheng.common.exception.ServiceException;
import com.jincheng.common.exception.user.*;
import com.jincheng.common.utils.DateUtils;
import com.jincheng.common.utils.MessageUtils;
import com.jincheng.common.utils.StringUtils;
import com.jincheng.common.utils.http.HttpUtils;
import com.jincheng.common.utils.ip.IpUtils;
import com.jincheng.framework.config.properties.WeChatProperties;
import com.jincheng.framework.manager.AsyncManager;
import com.jincheng.framework.manager.factory.AsyncFactory;
import com.jincheng.framework.security.context.AuthenticationContextHolder;
import com.jincheng.system.service.ISysConfigService;
import com.jincheng.system.service.ISysUserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 登录校验方法
 *
 * @author DairyJay
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 微信服务接口地址
     */
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 登录验证
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    public String login(LoginBody loginBody, boolean isAdminPanel) {
        String username = loginBody.getUsername();
        String password = loginBody.getPassword();
        // 验证码校验
        validateCaptcha(loginBody.getUsername(), loginBody.getCode(), loginBody.getUuid());
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 验证是否可以登录管理员后台
        if (isAdminPanel && !loginUser.getUser().isBackUser()){
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginUser.getUsername(), Constants.LOGIN_FAIL, MessageUtils.message("user.login.admin.panel.permission")));
            return null;
        }

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 更新用户登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }

    /**
     * 微信登录接口
     * @param wxLoginBody 微信登录登录信息
     * @return Map token+是否是新用户
     */
    public String wxLogin(WxLoginBody wxLoginBody) {
        String openid = getOpenid(wxLoginBody.getCode());
        SysUser user = userService.selectUserByOpenId(openid);
        if (user == null){
            user = new SysUser();
            user.setOpenid(openid);
            user.setUserName("defaultUserName_" + UUID.randomUUID().toString().substring(24));
            user.setNickName(wxLoginBody.getNickName());
            user.setAvatar(wxLoginBody.getAvatar());
            user.setRoleIds(new Long[]{5L});
            userService.insertUser(user);
            recordLoginInfo(user.getUserId());
        }

        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));

        return tokenService.createToken(loginUser);
    }

    /**
     * 根据临时登录凭证获取openid
     * @param code 临时登录凭证
     * @return openid
     */
    private String getOpenid(String code){
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getAppSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpUtils.sendGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        if (openid == null){
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(code, Constants.LOGIN_FAIL, MessageUtils.message("user.unknown.error")));
            throw new RuntimeException("登录失败");
        }
        return openid;
    }
}
